<!DOCTYPE html>
<html lang='zh-CN'>

<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="bootstrap.min.css" rel="stylesheet">
    <title>新三国ol_html版本_战斗</title>

    <style>
        h2 {
            font-size: xx-small;
        }
        .shake {
            animation: shake 800ms ease-in-out;
        }
       @keyframes shake {
           10%, 90% { transform: translate3d(-1px, 0, 0); }
           20%, 80% { transform: translate3d(+2px, 0, 0); }
           30%, 70% { transform: translate3d(-4px, 0, 0); }
           40%, 60% { transform: translate3d(+4px, 0, 0); }
           50% { transform: translate3d(-4px, 0, 0); }
       }
       
    </style>
</head>

<body>


    <div class="container-fluid text-center">
        <nav class="navbar navbar-expand-lg bg-light">
            <div class="container-fluid">
                <div class="btn-group">
                    <img src="home.png" alt="Logo" width="48" height="48" class="d-inline-block align-text-center">

                    <button class="btn dropdown-toggle  align-text-center dropdown-toggle-split"
                        data-bs-toggle="dropdown" aria-expanded="false">村口</button>

                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="wabao.html">宝石矿洞</a></li>
                        <li><a class="dropdown-item" href="home.html">新手村</a></li>
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li><a class="dropdown-item" href="#">宝藏</a></li>
                    </ul>
                </div>

                <div> <span id="tips">人数:1 </span> <button class="btn btn-success" disabled id="placeBtn">更多</button>
                </div>

                <!-- Example split danger button -->
                <div class="btn-group">
                    <button type="button" class="btn btn-danger dropdown-toggle dropdown-toggle-split"
                        data-bs-toggle="dropdown" aria-expanded="false">
                        菜单
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="btnFunc('info')">状态</a></li>
                        <li><a class="dropdown-item" href="#" onclick="btnFunc('bag')">背包</a></li>
                        <li><a class="dropdown-item" href="#">宝库</a></li>
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li><a class="dropdown-item" href="#">熔炉</a></li>
                        <li><a class="dropdown-item" href="#">武器</a></li>
                        <li><a class="dropdown-item" href="#">副将</a></li>
                        <li><a class="dropdown-item" href="#">排行</a></li>
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li><a class="dropdown-item" href="#">攻略</a></li>
                        <li><a class="dropdown-item" href="#">有奖反馈</a></li>
                        <li><a class="dropdown-item" href="#">登出</a></li>
                    </ul>
                </div>
            </div>
        </nav>
        <div class="modal fade modal-fullscreen" id="mymodal" data-bs-keyboard="false" tabindex="-1"
            aria-labelledby="staticBackdropLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">

                    <div class="modal-body">
                        <div id="info"></div>
                    </div>

                </div>
            </div>
        </div>

        <div class="modal fade" id="msgmodal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
            aria-labelledby="staticBackdropLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">发言</h5>
                    </div>
                    <div class="modal-body">
                        <input type="text" maxlength="20" class="form-control" id="msgInput">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal fade" id="renamemodal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
        aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">改名(限时免费)</h5>
                </div>
                <div class="modal-body">
                    <input type="text" maxlength="5" class="form-control" id="nameInput">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>
        <div class="modal fade " id="bagmodal" data-bs-keyboard="false" tabindex="-1"
            aria-labelledby="staticBackdropLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-scrollable">

                <div class="modal-content">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <div class="modal-body">

                        <table class="table">

                            <tbody id="tbd">
                                <tr>
                                    <td scope="row">物品</td>
                                    <td>数量</td>
                                    <td>操作</td>
                                </tr>



                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
        <span id="puser" class="fs-1"></span><br/>
        <div class="progress" id="ehp" role="progressbar" aria-label="Danger example" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
            <div class="progress-bar bg-danger" style="width: 100%"><span style="color:black;">盗贼：100</span></div>
          </div>
          <br/>
             <div class="progress" id="mhp" role="progressbar" aria-label="Danger example" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">
            <div class="progress-bar bg-danger" style="width: 100%"><span style="color:black;">我：100</span></div>
          </div>
        <div class="row">
            <div class=" border" id="canvas-container" style="padding: 0; margin: 0; height: 200px;">
              <canvas id="canvas" class="img-responsive" style="border: 1px solid #0f0; margin: 0; padding: 0">
                Sorry. your browser not support canvas.
              </canvas>
            </div>
          </div>
        <div class="container text-center">
            <div class="row">
              <div class="col">
                <button class="btn btn-success" onclick="btnFunc('attack')" id="attackBtn">攻击</button>

              </div>
              <div class="col-6">
                <button class="btn btn-success" onclick="btnFunc('defend')" id="renameBtn">防御</button>

              </div>
              <div class="col">
                <button class="btn btn-success" onclick="btnFunc('recruit')" id="renameBtn">招降</button>

              </div>
            </div>
         
          </div>

        <hr />
        <div class="accordion" id="accordionExample">
            <div class="accordion-item">
              <h2 class="accordion-header" id="headingOne">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
                  底部消息
                </button>
              </h2>
              <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
                <div class="accordion-body">
                    <ul class="nav nav-tabs" id="myTab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link " id="home-tab" data-bs-toggle="tab" data-bs-target="#home-tab-pane"
                                type="button" role="tab" aria-controls="home-tab-pane" aria-selected="false">区聊</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile-tab-pane"
                                type="button" role="tab" aria-controls="profile-tab-pane" aria-selected="false">教派</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact-tab-pane"
                                type="button" role="tab" aria-controls="contact-tab-pane" aria-selected="false">跨区</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="disabled-tab" data-bs-toggle="tab"
                                data-bs-target="#disabled-tab-pane" type="button" role="tab" aria-controls="disabled-tab-pane"
                                aria-selected="true">系统</button>
                        </li>
                        <button class="btn btn-success" onclick="btnFunc('msgBtn')" id="msgBtn">发言</button>
            
                    </ul>
            
                    <div class="tab-content" id="myTabContent">
                        <div class="tab-pane fade " id="home-tab-pane" role="tabpanel" aria-labelledby="home-tab" tabindex="0">
            
                        </div>
                        <div class="tab-pane fade" id="profile-tab-pane" role="tabpanel" aria-labelledby="profile-tab" tabindex="0">
            
                        </div>
                        <div class="tab-pane fade" id="contact-tab-pane" role="tabpanel" aria-labelledby="contact-tab" tabindex="0">
            
            
                        </div>
                        <div class="tab-pane fade active show" id="disabled-tab-pane" role="tabpanel" aria-labelledby="disabled-tab"
                            tabindex="0">
            
                        </div>
                    </div>
                </div>
              </div>
            </div>
          
          </div>
     


    </div>
    <script src="popper.min.js"></script>
    <script src="bootstrap.min.js"></script>
    <script src="jquery-3.6.0.min.js"></script>
    <script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    <script src="person.js"></script>
    <script src="util.js"></script>
    <script src="net.js"></script>
    <script src="msgMgr.js"></script>
</body>

<script>
    var url = "https://2020cn.cn/hxsg/api/user_mgr";
    var goodsList = [];
    var checkedInfoBase = true;
    var img2=new Image()
    img2.src="road.png";


    var player = new Person("player",100,50,21,21,"player_header1.png","body_normal_wushi1.png","player_footer1.png");
    var enemy = new Person("enemy",100,50,21,21,"header1.png","body1.png","footer_normal2.png");
    
    var c = document.getElementById("canvas");

    var ctx = c.getContext("2d");
    var timer = setInterval(gamedraw,1000/10);
    var timestart = 0;
    var timecouts = 0;
    function gamedraw(){
        timecouts++;
        if(timecouts>10000)
        timecouts=0;
        var ctx = document.getElementById('canvas').getContext('2d');
        var canvasContainer = document.getElementById('canvas-container');
        ctx.canvas.width  = canvasContainer.offsetWidth-2;
        ctx.canvas.height = canvasContainer.offsetHeight-2;
        ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
        ctx.drawImage(img2,0,0,ctx.canvas.width,ctx.canvas.height)
        ctx.scale(-1,1);
        ctx.translate(-ctx.canvas.width,0);
        player.anim(timecouts,ctx.canvas.width-enemy.x);
        player.show(ctx);
        ctx.scale(-1,1);
        ctx.translate(-ctx.canvas.width,0);
        enemy.anim(timecouts, ctx.canvas.width-player.x);

        enemy.show(ctx);
        if(enemy.anistate == 0){
            let rect = this.canvas.getBoundingClientRect()
           
            //player.x = ctx.canvas.width -mouse.x;
            //console.log(mouse);
        }
    }
    var CanvasAutoResize = {
        draw: function() {
          var ctx = document.getElementById('canvas').getContext('2d');
          var canvasContainer = document.getElementById('canvas-container');
          ctx.canvas.width  = canvasContainer.offsetWidth-2;
          ctx.canvas.height = canvasContainer.offsetHeight-2;
         
        },
       
        initialize: function(){
          var self = CanvasAutoResize;
          self.draw();
          $(window).on('resize', function(event){
            self.draw();
          });
        }
      }
       
      $(function(argument) {
        CanvasAutoResize.initialize();
      });
    $(document).ready(function () {
        if ($.cookie("user_id") == null) {
            alert("请登录!");
            window.location.href = "index.html";
            return;
        }
        $('#puser')[0].innerHTML = "盗贼 vs " + getKvFromCookie("name");

        var user_id = $.cookie('user_id');
        $.post(
            url,
            {
                "action": "getUserInfoAll",
                "user_id": user_id
            },
            function (res) {
                const resobj = JSON.parse(res);
                console.log(resobj.data[0])
                var ele = (resobj.data)[0];
                $.cookie("user", JSON.stringify(ele), { expires: 7 });
                //console.log(ele)
                var infoBaseStr = ["<h2 id='vtype'>" + ele.level + "级" + getJobNameByJobId(ele.job) + "</h2>",
                "<h2>id:" + (1000 + parseInt(ele.id)) + "</h2>",
                "<h2>名字:" + ele.name + "</h2>",
                "<h2>性别：" + (parseInt(ele.gender) == 0 ? "男" : "女") + "</h2>",
                "<h2>国家：" + (parseInt(ele.contry) == 0 ? "魏" : (parseInt(ele.contry) == 1 ? "蜀" : "吴")) + "</h2>",
                "<h2>居住地：" + (parseInt(ele.contry) == 0 ? "洛阳" : (parseInt(ele.contry) == 1 ? "成都" : "建业")) + "</h2>",
                "<h2>当前体力值:" + (ele.phystr) + "</h2>"].join("\n");
                var tmp = ["<h2>生命：" + (ele.hp) + "/" + ele.hpmax + "</h2>",
                "<h2>精力：" + (ele.mp) + "/" + ele.mpmax + "</h2>",
                "<h2>攻击：" + (ele.attack) + "</h2>",
                "<h2>防御：" + (ele.defence) + "</h2>",
                "<h2>速度：" + (ele.speed) + "</h2>",
                "<h2>金币：" + (ele.coin) + "</h2>",
                "<h2>银两：" + (ele.tael) + "</h2>",
                    "<div class='form-check'>",
                "<input class='form-check-input' type='checkbox' onclick='checkbox(this)' value='' id='flexCheckDefault' checked='" + checkedInfoBase + "'>",
                    "<label class='form-check-label' for='flexCheckDefault'>",
                    "个人信息常驻",
                    "</label></div>"
                ].join("\n");
                var node = $(tmp);
                var nodeInfoBase = $(infoBaseStr);
                $("#info").after(node);
                $("#infoBase").append(nodeInfoBase);

            }
        );


        var valInput = $("#nameInput");
        document.getElementById("renamemodal").addEventListener('hide.bs.modal', event => {
            if (valInput.val().length > 0 && valInput.val().length < 5) {
                //regist
                var user_id = $.cookie('user_id');
                var content = valInput.val();
                var type = 3;
                var oldname = getKvFromCookie("name");
                netUpdateUserByKv(user_id,"name", content, 1, function() {
                    //update local
                   // setKvFromCookieBag("15", getKvFromCookieBag("15") -1);
                    setKvFromCookieUser("name", content);
                    //updateBagView();
                    $('#puser')[0].innerHTML = "欢迎:" + getKvFromCookie("name");

                });
                msgMgr.net.sendMsg("1000","系统", "玩家("+oldname+")说,我改名了,以后就叫我("+content+")吧", 3, () => {
                    msgMgr.net.getMsgByType(3);
                });
            } else {
                alert("格式输入错误")
            }
        })
        var msgInput = $("#msgInput");
        document.getElementById("msgmodal").addEventListener('hide.bs.modal', event => {
            if (msgInput.val().length > 0 && msgInput.val().length < 20) {
                //regist
                var user_id = $.cookie('user_id');
                var content = msgInput.val();
                var type = getCurrentMsgType();
                msgMgr.net.sendMsg(user_id,getKvFromCookie("name"), content, type, () => {
                    msgMgr.net.getMsgByType(type);
                });
            } else {
                alert("格式输入错误")
            }
        })
        msgMgr.net.getMsgByType(getCurrentMsgType());
        const triggerTabList = document.querySelectorAll('#myTab button')
        triggerTabList.forEach(triggerEl => {
            triggerEl.addEventListener('click', function () {
                msgMgr.net.getMsgByType(getCurrentMsgType());

            })
        })
    });


    function checkbox(obj) {
        checkedInfoBase = obj.checked;
        var colNode = document.getElementById("collapseExample");
        if (obj.checked)
            colNode.classList.add("show");
        else
            colNode.classList.remove("show");


    }
    function setProgBarById(id,val,text){
        var bar = $("#"+id);
        var subbar = $("#"+id+">div");
        var subbarspan = $("#"+id+">div>span");
        bar.attr("aria-valuenow",val)
        subbar.attr("style","width:"+(parseInt(val))+"%");
       // subbar.text(text);
       subbarspan.text(text);
    }
    function btnFunc(str) {
        var user_id = $.cookie('user_id');

        if (str == 'bag') {
            updateBag();

        } else if (str == "info") {


            $("#mymodal").modal("show");
        } else if (str == "msgBtn") {
            if ((parseInt(user_id) != 1000 && parseInt(user_id) != 1) && getCurrentMsgType() == 3)
                alert("系统消息不能发言")
            else
                $("#msgmodal").modal("show");

        }else if (str == "attack") {
            $("#attackBtn").attr("disabled",true);
            var ehp = $("#ehp");
            var mhp = $("mhp");
            timecouts=0;
            var ehpv = ehp.attr("aria-valuenow");
            if(parseInt(player.speed) > parseInt(enemy.speed)){
                var realAtk = player.attack-enemy.defence;
                var newhp = ehpv-realAtk;
                if(newhp> 0){
                    this.player.anistate = 1;
                    setProgBarById("ehp",newhp,"盗贼:"+newhp)

                }else{
                    setProgBarById("ehp",0,"盗贼:"+newhp)
                    enemy.anistate = 2;
                    player.anistate = 3;
                    console.log("胜利")

                }
                
            }
         

        }
    }

    function bagUse(goods_id_str) {
        //logic
        //try net counts -
        var user_id = $.cookie('user_id');

        if (goods_id_str == "15") {
            netSendAddGoods(user_id,"15", "-1", () => {
                var countsbase = getKvFromCookie("tael");
                var randcounts = generateRandomInteger(1, 100000);
                var newcounts = randcounts + parseInt(countsbase);

                //notify
                if(randcounts > 80000)
                msgMgr.net.sendMsg("1000","系统",getKvFromCookie("name")+"运气太好了打开小银袋获得"+randcounts+"银两",3,()=>{
                    msgMgr.net.getMsgByType(3);
                });
                netUpdateUserByKv(user_id,"tael", newcounts, 0, function() {
                    //update local
                    setKvFromCookieBag("15", getKvFromCookieBag("15") -1);
                    setKvFromCookieUser("tael", newcounts);
                    updateBagView();

                });
            });
        } else if (goods_id_str == "5") {
            if (parseInt(getKvFromCookieBag("5")) > 0) {
                netSendAddGoods(user_id,"5", "-1", () => {
                    var countsbase = getKvFromCookie("phystr");
                    var newcounts = 50 + parseInt(countsbase);
                    netUpdateUserByKv(user_id,"phystr", newcounts, 0, function(){
                        //update local
                        setKvFromCookieBag("5", getKvFromCookieBag("5") - 1);
                        setKvFromCookieUser("tael", newcounts);
                        //update view
                     updateBagView();

                    });
                });
            }

        }

    }

  
// Event Listeners
addEventListener("mousemove", function (event) {
    mouse.x = event.clientX;
    mouse.y = event.clientY;
  });
  
  addEventListener("resize", function () {
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    init();
  });
  
var mouse = {
    x: innerWidth / 2,
    y: innerHeight / 2
  };
  var moveItv;
  document.addEventListener("touchstart", function (e) {
   // e.preventDefault();
    mouse.x = e.targetTouches[0].clientX;
    mouse.y = e.targetTouches[0].clientY;
    var msx =  ctx.canvas.width -mouse.x;
    var msy = mouse.y-window.canvas.getBoundingClientRect().y;
    clearInterval(moveItv);

    moveItv=setInterval(()=>{
    player.moveTo(msx,msy);
    if(Math.abs(player.x - msx)<5 && Math.abs(player.y - msy)<5)
        clearInterval(moveItv);
    },40);
    console.log("touchstart")
  });
  
  document.addEventListener("touchmove", function (e) {
    mouse.x = e.targetTouches[0].clientX;
    mouse.y = e.targetTouches[0].clientY;
  });
     
   
    function updateBagView(){
        $("#tbd").children().remove();
        var objlist =  JSON.parse($.cookie("bag"));

        for (let index = 0; index < objlist.length; index++) {
            //tael and coin don't show

            if ((parseInt(objlist[index]["goods_id"]) !== 16 && parseInt(objlist[index]["goods_id"]) !== 17)) {
                var node = $("<tr><td scope='row'>" + getGoodsNameByGid(objlist[index]["goods_id"]) + "</td><td>" + objlist[index]["counts"] + "</td><td><button onclick='bagUse("+objlist[index]["goods_id"]+")' "+(parseInt(objlist[index]["counts"])==0?'disabled':'')+">使用</button></td> </tr>");
                $("#tbd").append(node);
            }
        }
    
          

    }
    function updateBag() {
        var user_id = $.cookie('user_id');
        $.post(
            url,
            {
                "action": "getUserGoodsList",
                "user_id": user_id
            },
            function (res) {
                const resobj = JSON.parse(res);
                console.log(resobj.data);
                $.cookie("bag", JSON.stringify(resobj.data), { expires: 7 });
                updateBagView();
                $("#bagmodal").modal("show");

            }
        );

    }
    function updateCookieFromNet() {
        var user_id = $.cookie('user_id');

        $.post(
            url,
            {
                "action": "getUserInfoAll",
                "user_id": user_id
            },
            function (res) {
                console.log(res);
                const resobj = JSON.parse(res);
                console.log(resobj.data[0])
                var ele = (resobj.data)[0];
                counts = parseInt(ele.phystr);
                document.getElementById("tips").innerText = "体力：" + counts;
                $.cookie("user", JSON.stringify(ele), { expires: 7 });
            }
        );
    }
    function netUpdateUserByKv(user_id, key, val, val_type, cb) {
        $.post(
            url,
            {
                "action": "updateUserKvByid",
                "user_id": user_id,
                "key": key,
                "val": val,
                "val_type": val_type
            }, function (res) {
                if (cb) {
                    cb();
                    
                }
            }
        );
    }

    function netUseGoods(gid, counts) {

        var user_id = $.cookie('user_id');
        $.post(
            url,
            {
                "action": "addUserGoods",
                "user_id": user_id,
                "goods_id": gid,
                "counts": counts
            },
            function (res) {


            }
        );
    }
    function netSendAddGoods(user_id, gid, counts, cb) {

        $.post(
            url,
            {
                "action": "addUserGoods",
                "user_id": user_id,
                "goods_id": gid,
                "counts": counts
            },
            function (res) {
                //if add prop for user
                if(cb)
                cb();
            }
        );
    }
    function shake(elemId) {
        let elem = document.getElementById(elemId)
        if (elem) {
            elem.classList.add('shake')
            setTimeout(() => { elem.classList.remove('shake') }, 400)
        }
    }
    
    // 当点击某个元素时抖动
    
    
</script>

</html>